<template>
  <el-drawer @close="cancel" v-model="drawer">
    <template #header>
      <h4>分配角色</h4>
    </template>
    <el-form label-width="110px">
      <el-form-item label="用户姓名">
        <el-input
          placeholder="用户姓名"
          :disabled="true"
          v-model="RoleData.username"
        ></el-input>
      </el-form-item>
      <el-form-item label="职位列表">
        <el-checkbox
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
        <el-checkbox-group
          v-model="userRole"
          @change="handleCheckedCitiesChange"
        >
          <!-- label表示收集的数据,要和userRole保持一致 -->
          <el-checkbox v-for="role in allRole" :key="role.id" :label="role">
            {{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button size="default" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="saveUserRole($parent)">
          确定
        </el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { reqAllRoleAndCurUserRole, reqSetUserRole } from '@/api/acl/user'
import type {
  recordsData,
  setUserRoleRequestData,
  ResponseRole,
  roleObj,
} from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'

// checkbox数据
const checkAll = ref(false)
const isIndeterminate = ref(true)
const userRole = ref<roleObj[]>([])
let allRole = <any>[]

const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRole : []
  console.log(userRole.value)
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRole.length
  // 全选中时半选中去除状态
  isIndeterminate.value = checkedCount > 0 && checkedCount < allRole.length
}
// drawer数据
const drawer = ref(false)
const RoleData = ref<any>({})
const showDrawer = async (row: recordsData) => {
  const res: ResponseRole = await reqAllRoleAndCurUserRole(row.id as number)
  if (res.code === 200) {
    allRole = res.data.allRolesList
    userRole.value = res.data.assignRoles
  }
  RoleData.value = row
  drawer.value = true
}
// 点击保存
const saveUserRole = async ($parent: any) => {
  const paramsData: setUserRoleRequestData = {
    userId: RoleData.value.id,
    roleIdList: userRole.value.map((item) => item.id),
  }
  const res = await reqSetUserRole(paramsData)
  if (res.code === 200) {
    cancel()
    $parent.getUserList()
    ElMessage.success('分配成功')
  }
}
const cancel = () => {
  drawer.value = false
}
defineExpose({
  showDrawer,
})
</script>
<script lang="ts">
export default {
  name: 'userSetRole',
}
</script>
<style lang="scss" scoped></style>
